package com.victor.pomelo.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.authz.permission.WildcardPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.victor.pomelo.dao.ResourceMapper;
import com.victor.pomelo.model.Menu;
import com.victor.pomelo.model.Resource;
import com.victor.pomelo.service.ResourceService;

@Service
public class ResourceServiceImpl implements ResourceService {

	@Autowired
	private ResourceMapper resourceMapper;

	@Override
	public Resource createResource(Resource resource) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Resource updateResource(Resource resource) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void deleteResource(Long resourceId) {
		// TODO Auto-generated method stub

	}

	@Override
	public Resource findById(Long resourceId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Resource> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Set<String> findPermissions(Set<Long> resourceIds) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Resource> findMenus(Set<String> permissions) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Menu> findMainmenus(Set<String> permissions) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 通过用户名查询用户名可以使用的所有菜单子菜单列表
	 */
	@Override
	public Map<Long, Resource> findResources(Set<String> permissions) {

		Map<Long, Resource> ownerResources = new HashMap<Long, Resource>();

		List<Resource> allResources = resourceMapper.findAll();
		for (Resource resource : allResources) {
			if (hasPermission(permissions, resource)) {
				ownerResources.put(resource.getResourceid(), resource);
			}
		}

		return ownerResources;
	}

	private boolean hasPermission(Set<String> permissions, Resource resource) {
		if (StringUtils.isEmpty(resource.getPermission())) {
			return true;
		}
		for (String permission : permissions) {
			WildcardPermission p1 = new WildcardPermission(permission);
			WildcardPermission p2 = new WildcardPermission(
					resource.getPermission());
			if (p1.implies(p2) || p2.implies(p1)) {
				return true;
			}
		}
		return false;
	}

}
